#!/usr/bin/env ruby
# - pr_url
# - project_name
# majun-codecheck

require 'json'
require 'rest-client'
require "#{ENV['LKP_SRC']}/lib/log.rb"
require "#{ENV['LKP_SRC']}/lib/write_json.rb"

MAJUN_CODECHECK_URL = "https://majun.osinfra.cn/api/ci-backend/ci-portal/webhook/codecheck"

class MajunCodecheck
  def initialize
    @resource = RestClient::Resource.new(MAJUN_CODECHECK_URL)
    @static_token = ENV["secrets_static_token"]
    @pr_url = ENV["pr_url"]
    @project_name = ENV["project_name"]
  end

  def get_dynamic_token
    data = { :static_token => @static_token }

    begin
      response = @resource['v1/token'].post(data.to_json, :content_type => 'application/json')
    rescue Exception => e
      log_error "Failed to get dynamic token from Majun: #{data.to_json} => #{e.message}"
      raise e
    end
      
    raise "Failed to get dynamic token from Majun: #{data.to_json} => #{response}" unless response.code == 200
 
    JSON.parse(response.body)["data"]
  end

  def wait_codecheck_finish(data)
    while true
      begin
        response = @resource["v1/task/status"].post(data.to_json, :content_type => 'application/json')
      rescue Exception => e
        log_warn "Failed to query codecheck result from Majun: #{e.message}"
      end
      
      body = JSON.parse(response.body)
      log_info response.body
      code = body["code"]
      
      case code
      when "100"
        log_info "Majun's codecheck service is running, waiting for result..."
      when "200"
        log_info "Succeed in getting codecheck result from Majun: #{body}"
        write_json body, "majun-codecheck-result"
        break
      when "500"
        msg = body["msg"]
        raise "Failed to get codecheck result from Majun: #{msg}"
      else
        log_warn "Unknown code of response: #{code}"
      end

      log_info "Waiting 30 seconds for next query..."
      sleep 30
    end
  end

  def run
    token = get_dynamic_token
    
    data = {
      :pr_url => @pr_url,
      :token => token,
      :projectName => @project_name,
    }

    begin
      response = @resource['v1/task'].post(data.to_json, :content_type => 'application/json')
    rescue Exception => e
      log_error "Failed to create codecheck task from Majun: #{data.to_json} => #{response}"
      raise e
    end
      
    raise "Failed to create codecheck task from Majun: #{response}" unless response.code == 200

    body = JSON.parse(response.body)
    query_data = {
      :token => token,
      :uuid => body["uuid"],
      :task_id => body["task_id"]
    }

    wait_codecheck_finish query_data
  end
end

MajunCodecheck.new.run
